import { getPage, getImage } from '../../utils/config';
import { http, promisify, $empty, $toast, Validate } from '../../utils/utils';
import uploadImage from '../../utils/aliyunoss/uploadAliyun';
import api from '../../utils/api';
import wxApi from '../../utils/wxApi';
const app = getApp();

Page({

    /**
     * 页面的初始数据
     */
    data: {
        refundShow: false,
        refund: '',
        explain: '',
        phoneNumber: '',
        uploadPic: [getImage.uploadDefault],
        picCount: 4,
        columns: ['我不想买了', '信息填写错误，重新拍', '卖家缺货', '同城见面交易', '付款遇到问题', '拍错了', '其他原因'],
        columns1: ['无理由换货', '尺码颜色不合适', '商品发错','少件、漏发', '收到商品时有划痕或破损','商品实物与描述不符','商品质量问题','快递无跟踪记录', '与商家协商一致', '未按约定时间发货', '其他原因'],
        columns2: ['无理由换货', '尺码颜色不合适', '商品发错', '收到商品时有划痕或破损', '与商家协商一致', '其他原因'],
    },

    toggle(type) {
        this.setData({
            [type]: !this.data[type]
        });
    },

    /**
     * 退货原因--选择器
     */
    applyRefund() {
        this.toggle('refundShow');
    },

    /**
     * 选择原因
     */
    refundChange(e) {
        const { value } = e.detail;
        
        this.setData({
            refundError: '',
            refund: value,
        });

        this.applyRefund();
    },

    /**
     * 退款说明
     */
    explainInput(e) {
        this.setData({
            explain: $empty(e.detail)
        });
    },

    /**
     * 联系电话
     */
    phoneNumberInput(e) {
        this.setData({
            phoneNumberError: '',
            phoneNumber: $empty(e.detail)
        })
    },

    /**
     * 上传图片--微信api
     */
    uploadImgClick() {
        let { uploadPic, picCount } = this.data;
        let count = picCount - uploadPic.length;

        promisify(wx.chooseImage)({
            count: count,
            sizeType: ['original', 'compressed'],
            sourceType: ['album', 'camera'],
        }).then((res) => {
            //先删除原有数组的最后一个
            uploadPic.splice(uploadPic.length - 1, 1);
            //后将原有的最后一个加入结尾
            res.tempFilePaths.push(getImage.uploadDefault);
            //生成新的集合
            uploadPic = [].concat(uploadPic, res.tempFilePaths);
            this.setData({ uploadPic });
        })
    },

    /**
     * 删除图片--操作数据
     */
    deleteImgClick(e) {
        const { dataset } = e.currentTarget || e.target;
        const { uploadPic } = this.data;

        uploadPic.splice(dataset.id, 1);

        this.setData({ uploadPic });
    },

    /**
     * 上传图片--网络请求
     */
    setUploadImage() {
        return new Promise((resolve, reject) => {
            const { uploadPic } = this.data;
            let list = [];

            if (uploadPic.length > 1){
                uploadPic.forEach((item, idx) => {
                    if (idx != uploadPic.length -1 ){
                        uploadImage({
                            filePath: item,
                            dir: "product",
                            success(res) {
                                list.push({
                                    base64str: res
                                });
                            },
                            fail(res) {
                                $toast(`第${idx}张图片上传失败`);
                            },
                            complete() {
                                if (idx == uploadPic.length - 2) {
                                    resolve(list);
                                }
                            },
                        });
                    }
                });
            } else {
                resolve(list);
            }
        })
    },

    /**
     * 发货前退款--网络请求
     */
    setCancelOrder(cb) {
        const { userId, products, uploadPic, refund, explain, phoneNumber } = this.data;

        http.post(api.default, {
            data: {
                action: 'cancelorderitempaied',
                userid: userId,
                reason: refund,
                remark: explain,
                itemid: products.item_id,
                mobile: phoneNumber,
            }
        }).then((res) => {
            cb && cb(res);
        })
    },

    /**
     * 发货后退换货--网络请求
     */
    setAftersaleOrder(cb) {
        const { userId, products, refund, explain, phoneNumber, applyType } = this.data;

        this.setUploadImage().then((res) => {
            http.post(api.default, {
                data: {
                    action: 'shouhoushenqing',
                    userid: userId,
                    reason: refund,
                    remark: explain,
                    item_id: products.item_id,
                    mobile: phoneNumber,
                    pic: JSON.stringify(res),
                    ordertype: applyType < 0 ? 2 : 3, //2=换货；3=退货
                }
            }).then((res) => {
                cb && cb(res);
            })
        })
    },

    /**
     * 提交申请--网络请求
     */
    refundForm(e) {
        Validate.check(this, this.addressValidate, e.detail.value, (res) => {
            if(res){
                const { products, source } = this.data;
                
                //发货前退款
                if(source > 0){
                    this.setCancelOrder((res) => {
                        this.jumpPages(res);
                    })
                }else {
                    this.setAftersaleOrder((res) => {
                        this.jumpPages(res);
                    })
                }
            }
        });
    },

    /**
     * 申请成功--路由挑战
     */
    jumpPages(res) {
        const { data } = res.data;
        const { products } = this.data;
        const pages = getCurrentPages()[getCurrentPages().length - 2];
        
        wx.redirectTo({
            url: `${getPage.aftersaleDetails}?id=${data.ID}`,
            success() {
                if (pages !== undefined || pages !== null) {
                    pages.applyRefund(products.orderid);
                }
            }
        });
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {

        //获取携带参数
        if(JSON.stringify(options) != '{}'){
            /**
             * @parems {Number} source 1 发货前退款 -1 发货后退换货
             * @parems {Number} applyType 1 发货后退款 -1 发货后换货
             */
            const products = JSON.parse(options.products);

            this.setData({
                phoneNumber: products.mobile,
                userId: options.userId,
                products: products,
                source: options.hasOwnProperty('source') ? 1 : -1,
                applyType: options.hasOwnProperty('applyType') ? 1 : -1,
            })
        }

        //获取验证规则
        Validate.rules('#refund,#phoneNumber', (res) => {
            this.addressValidate = res;
        });
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {
        
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    }
})